package com.jintoufs.service.customer.impl;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.google.common.collect.Lists;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.dao.customer.CustomerDAO;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.divided.Divided;
import com.jintoufs.domain.sys.Dictionary;
import com.jintoufs.logAnnotation.SystemServiceLog;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.divided.DividedService;
import com.jintoufs.service.sys.DictionaryService;
import com.jintoufs.service.user.PasswordHelper;
import com.jintoufs.util.CardCodeGenerator;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.uuid.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/1 0001.
 */
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerDAO customerDAO;
    @Resource
    private PasswordHelper passwordHelper;

    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;

    @Resource
    private DictionaryService dictionaryService;

    @Resource
    private DividedService dividedService;

    @Value("${smsAppid}")
    private Integer smsAppid;
    @Value("${smsAppkey}")
    private String smsAppkey;


    @Override
    public List<Customer> getByFilter(QueryFilters filters) {
        List<Customer> result = customerDAO.getByFilter(filters);
        return result;
    }

    @Override
    public List<Map<String, Object>> getByFilter2(QueryFilters filters) {
        List<Map<String, Object>> result = customerDAO.getByFilter2(filters);
        return result;
    }

    @Override
    public List<Customer> queryByParams(Map<String, Object> params) {
        return customerDAO.queryByParams(params);
    }

    @Override
    @SystemServiceLog(description = "新增客户")
    public Customer add(Customer customer) {
        try {
            Map map = new HashMap();
            map.put("userName", customer.getUserName());
            List<Customer> customers = customerDAO.queryByParams(map);
            if (!customers.isEmpty() && customers.size() > 0) {
                return null;
            }
            customer.setPassword(CardCodeGenerator.generateRandomPassword());
            ArrayList<String> params = new ArrayList<String>();
            params.add(customer.getPassword());
            List<Dictionary> list = dictionaryService.getDicByKeyNo("CREATE_CUSTOEMER");
            if (!list.isEmpty() && list.size() > 0) {
                int smsId=Integer.parseInt(list.get(0).getCaption().toString());
                sendSms(customer.getMobilePhone(), params,smsId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        passwordHelper.encryptPassword(customer);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", customer.getUserName());
        List<Customer> list = customerDAO.queryByParams(params);
        if (list == null || list.size() == 0) {
            customerDAO.insert(customer);
            return customer;
        } else {
            params.clear();
            params.put("mobilePhone", customer.getMobilePhone());
            list = customerDAO.queryByParams(params);
            if (list == null || list.size() == 0) {
                customerDAO.insert(customer);
                return customer;
            } else {
                return null;
            }
        }
    }

    @Override
    @SystemServiceLog(description = "修改客户")
    public void update(Customer customer) {
        customerDAO.update(customer);
    }

    @Override
    @SystemServiceLog(description = "删除客户")
    public void delete(String id) {
        customerDAO.delete(id);
    }

    @Override
    public Customer getById(String id) {
        return customerDAO.queryByPrimaryKey(id);
    }

    @Override
    public Customer initPassword(String id) {

        Customer customer = customerDAO.queryByPrimaryKey(id);
        customer.setPassword(CardCodeGenerator.generateRandomPassword());
        customer.setModified(Constants.USER_PASSWORD_NOT_MODIFY);
        ArrayList<String> params = new ArrayList<String>();
        params.add(customer.getPassword());
        List<Dictionary> list = dictionaryService.getDicByKeyNo("PASSWORD_RESET");
        if (!list.isEmpty() && list.size() > 0) {
            int smsId=Integer.parseInt(list.get(0).getCaption().toString());
            sendSms(customer.getMobilePhone(), params,smsId);
        }
        passwordHelper.encryptPassword(customer);
        customerDAO.update(customer);
        return null;
    }

    @Override
    public Customer getByToken(String token) {
        return customerDAO.getByToken(token);
    }

    @Override
    public Boolean auth(Map<String, Object> param) {
        return customerDAO.auth(param) > 0;
    }

    @Override
    public Map<String, Object> queryUserById(String id) {
        return customerDAO.queryUserById(id);
    }

    @Override
    public List<Customer> getUserByRoleName(String roleName) {
        return customerDAO.getUserByRoleName(roleName);
    }

    @Override
    public Customer addCustomer(Customer customer) {
        // sendSms(customer.getMobilePhone(),customer.getPassword());
        customer.setPassword(CardCodeGenerator.generateRandomPassword());
        passwordHelper.encryptPassword(customer);
        customerDAO.insert(customer);
        return customer;
    }

    /**
     * @param orderId    orderId
     * @param customerId 购买者Id
     * @param price      直客價（零售价）
     * @param actPrice 實際支付价格
     * @param sharePrice  订单結算价（分銷價）
     * @param provider   供应商
     * @param needBill   是否需要发票
     */
    @Override
    public void computDilivid(String orderId, String customerId, BigDecimal price, BigDecimal actPrice, BigDecimal sharePrice,
                              Customer provider, String needBill, String spreadId) {
        //购买人
        Customer customer = getById(customerId);
        //平台默认分润比例 0-1之间的一个小数
        Dictionary dictionary = dictionaryService.getDicByKeyNo(Constants.DEFAULT_DIVIDED_NUMBER).get(0);
        Dictionary trasFeedictionary = dictionaryService.getDicByKeyNo(Constants.DEFALUT_TRANS_FEE).get(0);
        BigDecimal defaultDividedNumber = new BigDecimal(dictionary.getKeyValue());
        //平台设置税率  0-1之间的一个小数
        dictionary = dictionaryService.getDicByKeyNo(Constants.DEFAULT_TAX).get(0);
        BigDecimal defaultTax = new BigDecimal(dictionary.getKeyValue());

        // 快遞費
        BigDecimal trasFee = new BigDecimal(0);
        if (trasFeedictionary != null && trasFeedictionary.getKeyValue() != null && !trasFeedictionary.getKeyValue().isEmpty()) {
            trasFee = new BigDecimal(trasFeedictionary.getKeyValue());
        }

        // 分润金额=直客价(零售价)-结算价(分销价)-税
        BigDecimal profit = price.subtract(sharePrice);
        if ("1".equals(needBill)) {
            //需要发票 全额利润-直客價*税率
            //TODO  如果不需要发票，则不扣税，那么，和分销商和供应商结算时候的税钱是谁知负？
            profit = profit.subtract(price.multiply(defaultTax));

        }

        //给供应商结算金额
        //分润系数
        BigDecimal dividedNumber = defaultDividedNumber;
        if ("0".equals(customer.getType().toString()) || "1".equals(customer.getType().toString())) {
            //购买者是供应商或者分销商,将利润全部返回


            saveDivided(orderId, customer, profit);

        } else if ("2".equals(customer.getType().toString())) {
            //购买者是推广者 获得分润为 (零售价-成本价-发票税钱)*（1-分销商设置分润比例）
            //如果有分销商，获得分润为 (零售价-成本价-发票税钱)*分销商设置分润比例

            Customer recommender = getById(customer.getRecommendId());
            if (!ValidUtil.isEmpty(recommender) && Constants.CUSTOMER_AUTH_STATUS_AUTHED.equals(recommender.getAuth())) {
                //如果有分销商，给分销商分润
                dividedNumber = new BigDecimal(recommender.getDividedNumber());
                BigDecimal divided_recommend = profit.multiply(dividedNumber);
                //记录分销商利润
                saveDivided(orderId, recommender, divided_recommend);
            }
            //给自己分润
            BigDecimal divide_spreaderSelf = profit.multiply(new BigDecimal("1").subtract(dividedNumber));
            //记录自己利润
            saveDivided(orderId, customer, divide_spreaderSelf);
        } else {
            //购买者是消费者
            //分销商
            Customer recommender = getById(customer.getRecommendId());
            //推广人
            Customer spreader = getById(spreadId);

            if (!ValidUtil.isEmpty(recommender) && Constants.CUSTOMER_AUTH_STATUS_AUTHED.equals(recommender.getAuth())
                    && ValidUtil.isEmpty(spreader)) {
                //1.如果只有分销商，没得推广人

                //记录分销商分润记录
                saveDivided(orderId, recommender, profit);
            } else if (!ValidUtil.isEmpty(recommender) && Constants.CUSTOMER_AUTH_STATUS_AUTHED.equals(recommender.getAuth())
                    && !ValidUtil.isEmpty(spreader) && Constants.CUSTOMER_AUTH_STATUS_AUTHED.equals(spreader.getAuth())

                    ) {
                if (spreader.getRecommendId() != null && spreader.getRecommendId().equals(recommender.getId())) {
                    //2.如果有分销商，也推广人，且推广人的推荐人是该分销商，则也给该推广人分润

                    //如果有推广人，给推广人分利润,分润系数为 1-设置的分润系数
                    BigDecimal divided_spread = profit.multiply(new BigDecimal("1").subtract(dividedNumber));
                    //记录推广人分润记录
                    saveDivided(orderId, spreader, divided_spread);
                    //如果有分销商则分润系数为分销商设置，如果没有分销商，分润系数为平台默认
                    //分销商分润系数
                    dividedNumber = new BigDecimal(recommender.getDividedNumber());
                    BigDecimal divided_recom = profit.multiply(dividedNumber);
                    //记录分销商分润记录
                    saveDivided(orderId, recommender, divided_recom);
                } else {
                    //3.如果有分销商，也推广人，且推广人的推荐人不是该分销商，则不给该推广人分润
                    //记录分销商分润记录
                    saveDivided(orderId, recommender, profit);
                }

            }
        }
    }

    private void saveDivided(String orderId, Customer customer, BigDecimal profit) {
        if (customer.getDivided() != null) {
            customer.setDivided(customer.getDivided().add(profit));
        } else {
            customer.setDivided(profit);
        }
        update(customer);
        Divided divided = new Divided();
        //分润记录id
        divided.setId(String.valueOf(snowflakeIdWorker.nextId()));
        //记录购买人id
        divided.setCustomerId(customer.getId());
        //记录购买人分润
        divided.setAmount(profit);
        divided.setOrderId(orderId);
        dividedService.saveDivided(divided);
    }


    public void sendSms(String mobile, ArrayList<String> params ,int smsId ) {
        try {
            SmsSingleSender sender = new SmsSingleSender(smsAppid, smsAppkey);
            SmsSingleSenderResult result = sender.sendWithParam("86", mobile, smsId, params, "", "", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List queryOrderByParams(Map params) {
        return customerDAO.queryOrderByParams(params);
    }

}
